import { useStore, observer } from '../../store'
import { Tabs } from 'antd'
import { useNavigate, useLocation } from 'react-router-dom'

function LayoutNavbar () {
  const { userStore, layoutStore } = useStore()
  const navigate = useNavigate()
  const location = useLocation()

  // 编辑tabs
  const editTabHandler = (key: string, type: 'add' | 'remove') => {
    if (type === 'remove') {
      // 关闭当前激活的页签，激活状态左移
      const targetIndex = layoutStore.tabs.findIndex(tab => tab.url === key)
      if (key === location.pathname && targetIndex >= 1) {
        navigate(layoutStore.tabs[targetIndex - 1].url, { replace: true })
      }
      layoutStore.removeTab(userStore.permissions[key])
    }
  }

  return (
    <Tabs
      type="editable-card"
      hideAdd
      activeKey={location.pathname}
      onTabClick={key => navigate(key)}
      onEdit={(key, type) => editTabHandler(key as string, type)}
    >
      {layoutStore.tabs.map(tab => (
        <Tabs.TabPane
          tab={tab.label}
          key={tab.url}
          closable={tab.url !== '/dashboard'}
        ></Tabs.TabPane>
      ))}
    </Tabs>
  )
}

export default observer(LayoutNavbar)
